//
//  UsefulUtil.m
//  NiuBanJinGold
//
//  Created by Billy on 15/9/24.
//  Copyright (c) 2015年 zzjr. All rights reserved.
//

#import "UsefulUtil.h"
#import "SFHFKeychainUtils.h"
@implementation UsefulUtil

+ (UIColor *) colorWithHexString: (NSString *) hexStringToConvert {
    
    NSString *cString = [[hexStringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor blackColor];
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

+ (BOOL)isMobileNumber:(NSString *)mobileNumber {
    
    if (mobileNumber.length != 11) {
        
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178
     * 联通号段: 130,131,132,155,156,185,186,145,176
     * 电信号段: 133,153,180,181,189,177
     */
    
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177
     */
    NSString *CT = @"^1(33|53|7[0-9]|8[019])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumber] == YES)
        || ([regextestcm evaluateWithObject:mobileNumber] == YES)
        || ([regextestct evaluateWithObject:mobileNumber] == YES)
        || ([regextestcu evaluateWithObject:mobileNumber] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


+(BOOL)isIDNumber:(NSString *)IDNumber{
    
    if (IDNumber.length == 15 || IDNumber.length == 18 ) {
        
        return YES;
        
    }else{
        return NO;
    }
}
//获取UUID
+(NSString *)getUDIDOfCurrentDevice{

//        return  [[[UIDevice currentDevice] identifierForVendor] UUIDString];;
    
    NSString *UUID = [SFHFKeychainUtils getPasswordForUsername:@"zf" andServiceName:@"zf" error:nil];
    
    if (UUID.length == 0) {
        
        UUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [SFHFKeychainUtils storeUsername:@"zf" andPassword:UUID forServiceName:@"zf" updateExisting:YES error:nil];
    }
   
    return [SFHFKeychainUtils getPasswordForUsername:@"zf" andServiceName:@"zf" error:nil];
}

+ (BOOL)isChinese:(NSString *)msg {
    
    if ([msg isEqualToString:@""]) {
        
        return NO;
    }
    
    for (int i = 0; i < [msg length]; i ++) {
        
        unichar a = [msg characterAtIndex:i];
        
        if ((int)a < 255) {
            
            return NO;
        }
    }
    
    return YES;
}

+ (NSString *)userRealRate {
    
    NSString *str_rate = [UserManager sharedUserManager].user.user_annualRate;
    NSString *str_rate_add = [UserManager sharedUserManager].user.user_ticketRate;
    
    CGFloat rate_total = [str_rate floatValue] + [str_rate_add floatValue];
    
    return  [NSString stringWithFormat:@"%.2f",rate_total];
}


+ (void) showAlertView:(NSString *) message {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:message message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

+ (NSArray *) allSupportedFonts {
    
    NSMutableArray *array = [NSMutableArray array];
    
    NSArray *familyNames = [UIFont familyNames];
    
    for( NSString *familyName in familyNames ){
        
        NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
        
        for( NSString *fontName in fontNames ){
            [array addObject:fontName];
        }
    }
    
    return  array;
}

+ (NSArray *) searchFontByFontName:(NSString *) fontName {
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:[self allSupportedFonts]];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@", fontName];
    
    return  [array filteredArrayUsingPredicate:predicate];
}

+ (UILabel *) labelCreationWithFrame:(CGRect ) frame textColor:(UIColor *) color fontName:(UIFont *) font text:(NSString *) text {
    
    UILabel *label_tmp = [[UILabel alloc] init];
    [label_tmp setTextColor:color];
    [label_tmp setFont:font];
    if (text) {
        
        [label_tmp setText:text];
    }
    [label_tmp setAdjustsFontSizeToFitWidth:YES];
    [label_tmp setFrame:frame];
    
    return  label_tmp;
}

+ (UIButton *) buttonCreationWithFrame:(CGRect ) frame textColor:(UIColor *) color fontName:(UIFont *) font text:(NSString *) text {
    
    UIButton *tmp = [[UIButton alloc] init];
    [tmp setTitle:text forState:UIControlStateNormal];
    [tmp setTitleColor:color forState:UIControlStateNormal];
    [tmp.titleLabel setFont:font];
    [tmp.titleLabel setAdjustsFontSizeToFitWidth:YES];
    [tmp setFrame:frame];
    [tmp.layer setCornerRadius:8.0];
    
    return  tmp;
}


+ (UIButton *) buttonCreationWithFrame:(CGRect ) frame textColor:(UIColor *) color fontName:(UIFont *) font text:(NSString *) text frontImageName: (NSString *) name {
    
    UIButton *tmp =  [self buttonCreationWithFrame:frame textColor:color fontName:font text:text];
    
    //TBD
    
    return  tmp;
}

+ (CALayer *) layerCreationWithFrame:(CGRect ) frame andContents:(id) content {
    
    CALayer *layer_tmp = [CALayer layer];
    [layer_tmp setFrame:frame];
    [layer_tmp setContents:content];
    
    return layer_tmp;
}

+ (CATextLayer *) textLayerCreationWithFrame: (CGRect ) frame  content:(NSString *) text fontSize:(CGFloat) size {
    
    CATextLayer *tmp = [CATextLayer layer];
    
    [tmp setFrame:frame];
    [tmp setString:text];
    [tmp setFontSize:size];
//    [tmp setAlignmentMode:kCAAlignmentCenter];
    [tmp setContentsScale:2.0];
    [tmp setWrapped:YES];
    
    return tmp;
}

+ (UIView *) viewCreationWithFrame:(CGRect ) frame backgroundColor:(UIColor *) color backGroundImage:(UIImage *) image {
    
    UIView *tmp = [[UIView alloc] initWithFrame:frame];
    
    [tmp setBackgroundColor:color];
    
    if (image) {
        
        [tmp.layer setContents:(__bridge id) image.CGImage];
    }
    
    return tmp;
}

+ (UIImageView *) imageViewCreationWithFrame:(CGRect ) frame image:(UIImage *) image {
    
    UIImageView *tmp = [[UIImageView alloc] initWithFrame:frame];
    
    [tmp setImage:image];
 
    return tmp;
}

// 存自定义object

+ (void) saveCustomObject:(NSObject *) obj intoUserDefaultByKey:(NSString *) key {
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:obj];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

// 取自定义object

+ (NSObject *) getCustomObjectByKey:(NSString *)key {
    
    NSData *getData =  [[NSUserDefaults standardUserDefaults] objectForKey:key];
    return [NSKeyedUnarchiver unarchiveObjectWithData:getData];
}

+ (void) clearAddressInfoFromUserDefault  {
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"province"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"city"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"country"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void) countDownMethodForButton:(UIButton *) button timeOutValue:(NSInteger ) value {
    
    __block int timeout = (int) value ; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置 特别注明：UI的改变一定要在主线程中进行
                [button setTitle:@"重新获取" forState:UIControlStateNormal];
            });
        }else{
            //            int minutes = timeout / 60;
            //            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            NSString *strTime2 = [NSString stringWithFormat:@"%.d", timeout];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [strTime integerValue] >= 10? [button setTitle:[NSString stringWithFormat:@"重发(%@)秒",strTime] forState:UIControlStateNormal] : [button setTitle:[NSString stringWithFormat:@"重发(%@)秒",strTime2] forState:UIControlStateNormal];
            });
            timeout--;
            
        }
    });
    
    dispatch_resume(_timer);
}

+ (CGSize)labelAutoCalculateRectWith:(NSString*)text FontSize:(CGFloat)fontSize MaxSize:(CGSize)maxSize {
    
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    
    paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
    
    NSDictionary* attributes =@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    //如果系统为iOS7.0；
    CGSize labelSize;
    
    if (![text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]){
        labelSize = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
        
    }else{ //如果是IOS6.0
        
            labelSize = [text boundingRectWithSize: maxSize
                                           options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine
                                        attributes:attributes
                                           context:nil].size;
        }
    
    labelSize.height=ceil(labelSize.height);
    labelSize.width=ceil(labelSize.width);
    
    return labelSize;
}


@end
